#coding=utf-8

import os
from BaseHTTPServer import BaseHTTPRequestHandler
import cgi
import json
import urllib
import urllib2

config = {}
api_url = "https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=%s"

class   PostHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        msg = self.path[1:]
        if msg == '':
            respond = {'status': 0, 'errno': -1, 'errmsg': 'empty msg'}
            self.wfile.write(json.dumps(respond))
        else:
            _api_url = api_url % (config['api_token'], config['chat_id'],msg)
            req = urllib2.Request(_api_url)
            res_data = urllib2.urlopen(req)
            res = res_data.read()
            print res
            self.wfile.write(res)

def StartServer():
    from BaseHTTPServer import HTTPServer
    sever = HTTPServer(("",config['port']),PostHandler)
    print "Start telegram bot server at %d:" % (config['port'])
    sever.serve_forever()

def readConfig():
    if os.path.exists(os.getcwd() + '/config.json'):
        f = open('config.json', 'r')
        global config
        fread = f.read()
        f.close()
        config = json.loads(fread, encoding='utf-8')
        print "config:\n" + fread
        config = byteify(config)
    else:
        print "config.json not exits\n"
        exit()

def byteify(input, encoding='utf-8'):
    if isinstance(input, dict):
        return {byteify(key): byteify(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode(encoding)
    else:
        return input

if __name__=='__main__':
    readConfig()
    StartServer()
